import { Suspense, useEffect, useState } from "react";
import { Routes,Route,useNavigate,useLocation,useParams, useSearchParams,Navigate } from "react-router-dom";
import routes from "./routes";
import { Mask,DotLoading,Toast } from 'antd-mobile'
import store from '../store';
import action from "../store/action";

const isCheckList = (path)=>{
    let { base:{ info } } = store.getState(),
        checkList = ['/personal','/store','/update']
    return !info && checkList.includes(path)
}

const Element = (props)=>{
    let {component:Component,meta,path} = props
    let isShow = !isCheckList(path)
    let [_,setRandom] = useState(0)
    //进行登录态校验
    /* let { base:{ info } } = store.getState(),
        checkList = ['/personal','/store','/update']
    if(!info && checkList.includes(path)){
        //如果info值不存在,并且跳转的地址是三个中的一个:从服务器获取登录者信息
        (async ()=>{
            let infoAction = await action.base.queryUserInfoAsync() //拿到返回的对象
            info = infoAction.info
            if(!info){
                //如果获取后还是不存在:没有登录
                Toast.show({
                    icon:'fail',
                    content:'请先登录'
                })
                return <Navigate to={{
                    pathname:'/login',
                    search:`?to=${path}`
                }} />
            }
            //如果获取到了信息,说明是登录的,我们派发任务把信息存储到容器中
            store.dispatch(infoAction)
        })()
    } */
    
    useEffect(()=>{
        if(isShow) return;
        (async ()=>{
            let infoAction = await action.base.queryUserInfoAsync() 
            let info = infoAction.info
            if(!info){
                Toast.show({
                    icon:'fail',
                    content:'请先登录'
                })
                navigate({
                    pathname:'/login',
                    search:`?to=${path}`
                },{replace:true})
                return;
            }
            store.dispatch(infoAction)
            setRandom(+new Date())
        })()
    })

    let { title='知乎日报-WebApp' } = meta || {}
    document.title = title

    const navigate = useNavigate(), location = useLocation(), params = useParams(), [usp] = useSearchParams()
    return <>
        {isShow ? <Component navigate={navigate} location={location} params={params} usp={usp}></Component> 
            : <Mask visible={true} opacity='thick'><DotLoading color='white' /></Mask>}
    </>
}

export default function RouterView(){
    return <Suspense fallback={<Mask visible={true} opacity='thick'><DotLoading color='white' /></Mask>}>
        <Routes>
            {routes.map((item)=>{
                let {path,name} = item
                return <Route key={name} path={path} element={<Element {...item}/>}></Route>
            })}
        </Routes>
    </Suspense>
}